<template>
  <el-card>
    <div class="fixed_header">
      <el-row type="flex" justify="space-between" style="margin-bottom: 10px">
        <el-col>
          <el-button size="small" @click="handleBack">返回上一页</el-button>
          <span style="font-weight: bold; margin-left: 10px">{{ title }}</span>
        </el-col>
        <div>
          <el-button type="primary" size="small" @click="handleSubmit"
            >提交</el-button
          >
        </div>
      </el-row>
    </div>
    <el-form
      class="form-container"
      :model="formModel"
      label-width="150px"
      :rules="rules"
      ref="form"
      size="small"
    >
      <el-card style="margin-bottom: 10px">
        <div slot="header" class="clearfix">
          <span>外派信息</span>
        </div>
        <el-form-item label="外派起止时间" prop="time">
          <el-date-picker
            v-model="formModel.time"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="外派车辆" required prop="details">
          <el-button type="primary" size="small" @click="handleAdd"
            >新增</el-button
          >
          <el-table :data="formModel.details">
            <el-table-column
              label="车牌照"
              align="center"
              prop="carLicensePlate"
            />
            <el-table-column label="车牌类型" align="center" prop="carType" />
            <el-table-column
              label="已绑定司机"
              align="center"
              prop="driverName"
              width="140"
            />
            <el-table-column
              label="司机手机号"
              align="center"
              width="160"
              :show-overflow-tooltip="true"
              prop="driverPhone"
            />
            <el-table-column label="泵送员姓名" align="center" prop="pumper">
              <template slot-scope="scope">
                <!-- <el-button type="text" size="small"> 请选择 </el-button> -->
                <el-select
                  v-model="scope.row.pumper"
                  multiple
                  filterable
                  reserve-keyword
                  placeholder="请填写"
                  :loading="loading"
                >
                  <el-option
                    v-for="item in allUser"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.$index)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-card>
      <el-card>
        <div slot="header" class="clearfix">
          <span>客户消息</span>
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="站点名称" prop="site">
              <el-input
                placeholder="请输入"
                v-model="formModel.site"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="站点联系人" prop="associates">
              <el-input
                placeholder="请输入"
                v-model="formModel.associates"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input
                placeholder="请输入"
                v-model="formModel.phoneNumber"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card style="margin-top: 10px" v-if="userId">
        <div slot="header" class="clearfix">
          <span>基础信息</span>
        </div>
        <el-row>
          <el-col :span="6">
            <el-form-item label="外派单Id">
              <span>{{ formModel.id }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间">
              <span>{{ formatDate(formModel.createTime) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最后编辑时间">
              <span>{{ formatDate(formModel.updateTime) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="外派单状态">
              <span>{{ formModel.dispatchState }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card style="margin-top: 10px">
        <el-form-item label="备注">
          <el-input
            type="textarea"
            placeholder="请输入备注"
            v-model="formModel.note"
            :row="2"
            style="width: 600px"
          ></el-input>
        </el-form-item>
      </el-card>
    </el-form>
    <!-- 外派车辆新增 -->
    <el-dialog
      title="新增外派车辆"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="mini"
        :inline="true"
        label-width="74px"
      >
        <el-form-item label="运营状态" prop="operationalStatus">
          <el-select
            v-model="queryParams.operationalStatus"
            @change="handleQuery"
          >
            <el-option :value="'在线'">在线</el-option>
            <el-option :value="'离线'">离线</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工作状态" prop="workingState">
          <el-select v-model="queryParams.workingState" @change="handleQuery">
            <el-option :value="'外派中'">外派中</el-option>
            <el-option :value="'空闲中'">空闲中</el-option>
            <el-option :value="'工作中'">工作中</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆类型" prop="carType">
          <el-select v-model="queryParams.carType" @change="handleQuery">
            <el-option :value="'砼车'">砼车</el-option>
            <el-option :value="'泵车'">泵车</el-option>
            <el-option :value="'铲车'">铲车</el-option>
            <el-option :value="'新华轩销售车'">新华轩销售车</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车牌号" prop="carLicensePlate">
          <el-input
            v-model="queryParams.carLicensePlate"
            placeholder="请输入车牌号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        :data="carsList"
        size="mini"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />``
        <el-table-column label="车辆类型" align="center" prop="carType" />
        <el-table-column label="车辆编号" align="center" prop="carNumber" />
        <el-table-column label="车牌照" align="center" prop="carLicensePlate" />
        <el-table-column label="工作状态" align="center" prop="workingState" />
        <el-table-column label="运营状态" align="center" prop="operationalStatus" />
        <el-table-column label="已绑定司机" align="center" prop="driverName" />
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  addDispatch,
  getDispatch,
  updateDispatch,
} from "@/api/system/dispatch";
import { listCars } from "@/api/service/cars";
import { formatDate } from "@/utils";
import { listUser } from "@/api/system/user";
export default {
  data() {
    return {
      userId: null,
      options: [],
      list: [],
      carsList: [],
      states: [
        "Alabama",
        "Alaska",
        "Arizona",
        "Arkansas",
        "California",
        "Colorado",
        "Connecticut",
        "Delaware",
        "Florida",
        "Georgia",
        "Hawaii",
        "Idaho",
        "Illinois",
        "Indiana",
        "Iowa",
        "Kansas",
        "Kentucky",
        "Louisiana",
        "Maine",
        "Maryland",
        "Massachusetts",
        "Michigan",
        "Minnesota",
        "Mississippi",
        "Missouri",
        "Montana",
        "Nebraska",
        "Nevada",
        "New Hampshire",
        "New Jersey",
        "New Mexico",
        "New York",
        "North Carolina",
        "North Dakota",
        "Ohio",
        "Oklahoma",
        "Oregon",
        "Pennsylvania",
        "Rhode Island",
        "South Carolina",
        "South Dakota",
        "Tennessee",
        "Texas",
        "Utah",
        "Vermont",
        "Virginia",
        "Washington",
        "West Virginia",
        "Wisconsin",
        "Wyoming",
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        operationalStatus: null,
        workingState: null,
        carType: null,
        carAttribution: null, // 车辆归属
        isDispatched: null,
        carNumber: null,
        carLicensePlate: null,
        driver: null,
      },
      total: 0,
      open: false,
      loading: false,
      formModel: {
        time: null,
        site: null, // 站点
        associates: null, // 站点联系人
        phoneNumber: null, // 站点联系人
        details: [],
        note: null,
      },
      allUser: [],
      rules: {
        site: [
          { required: true, message: "请输入站点名称", trigger: "blur,change" },
        ],
        time: [
          { required: true, message: "请输入起止时间", trigger: "blur,change" },
        ],
        details: [
          { required: true, message: "请选择外派车辆", trigger: "blur,change" },
        ],
        associates: [
          {
            required: true,
            message: "请输入站点联系人",
            trigger: "blur,change",
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号", trigger: "blur,change" },
        ],
      },
    };
  },
  methods: {
    formatDate,
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.options = this.allUser.filter((item) => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    handleDelete(index) {
      this.formModel.details.splice(index, 1);
    },
    submitForm() {
      this.formModel.details = this.selectCarList;
      this.list = this.states.map((item) => {
        return { value: `value:${item}`, label: `label:${item}` };
      });
      //   this.$refs.form
      this.open = false;
    },
    cancel() {
      this.open = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection);
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.selectCarList = selection;
    },
    /** 查询车辆基础信息列表 */
    getList() {
      this.loading = true;
      listCars(this.queryParams).then((response) => {
        this.carsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleAdd() {
      this.open = true;
      this.getList();
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.userId) {
            updateDispatch({
              ...this.formModel,
              beginDate: this.formModel?.time?.[0],
              endDate: this.formModel?.time?.[1],
              details: this.formModel?.details.map((item) => {
                return {
                  ...item,
                  driver: item.driverName,
                  pumper: item.pumper?.join(","),
                };
              }),
            }).then((res) => {
              this.$message.success("创建成功");
              this.handleBack();
            });
          } else {
            addDispatch({
              ...this.formModel,
              beginDate: this.formModel?.time?.[0],
              endDate: this.formModel?.time?.[1],
              details: this.formModel?.details.map((item) => {
                return {
                  ...item,
                  driver: item.driverName,
                  pumper: item.pumper?.join(","),
                };
              }),
            }).then((res) => {
              this.$message.success("创建成功");
              this.handleBack();
            });
          }
        } else {
          return false;
        }
      });
    },
    handleBack() {
      this.$router.push({
        path: "/logistics/dispatch",
      });
    },
    getAllUserList() {
      listUser({ pageNum: 1, pageSize: 10000 }).then((res) => {
        this.allUser = res.rows.map((item) => ({
          ...item,
          label: item.nickName,
          value: item.userId,
        }));
      });
    },
  },
  created() {
    this.getAllUserList();
    this.userId = this.$route.query.id;
    if (this.userId) {
      getDispatch(this.userId).then((response) => {
        this.formModel = {
          ...this.formModel,
          ...response.data,
          details: response.data?.details?.map((item) => {
            return {
              ...item,
              driverName: item.driverName,
              pumper: item?.pumper?.split(",") || [],
            };
          }),
          time: [response.data.beginDate, response.data.endDate],
        };
      });
    }
  },
  computed: {
    title() {
      return !this.$route?.query?.id ? "新增外派车辆" : "修改外派车辆";
    },
  },
};
</script>

<style lang="scss" scoped></style>
